define([
	'app',
	'lodash',
	"ngTable",
	'directives/ColumnList',//没用
	"directives/ScrollBar",
	"directives/group/GroupUserItems",
	"directives/common/OrgUserPicker",
	"resources/ContactsResource",
	'resources/ChatResource',
	"services/UserService",
	'services/TipsService'
], function(app, _ ) {

	var deps = [ '$state', "$document", "$timeout", "ContactsResource", "ChatResource", "UserService", "TipsService", "$stateParams"];

	function directive($state, $document, $timeout, ContactsResource, ChatResource, UserService, TipsService, $stateParams) {
		return {
			templateUrl: 'views/group/GroupItem.html',
			replace: true,
			scope: {
				item: '=fcGroupItem',
                selectSearch: '&?toChat'
			},
			link: function($scope, elem, attrs) {
				
				$scope.group = {}; //记录群组对象
		    	$scope.relateGroups = [];
		    	$scope.currentUser = UserService.getCurrentUser();
		    	
				queryData();
				initHeight();
				
				/**
		         * 加载数据
		         */
		        function queryData(){
		        	//通过groupId获取群组信息
		        	ContactsResource.queryGroupById($scope.item || $stateParams.groupId).success(function(group){//$stateParams.groupId
		        		if (group) {
		        			$scope.relateGroups = [];
		        			$scope.group = angular.copy(group);
		        			$scope.relateGroups = $scope.relateGroups.concat($scope.group.contractUser); //群组成员
		        		}
		        	});
		        }
		        
				/**
	        	 * 添加成员
	        	 */
	        	$scope.addUsers = function($chosenList){
	        		if($chosenList && $chosenList.length > 0){
	        			var addUserIds = [];
		        		for(var i = 0; i<$chosenList.length; i++){
		        			var flag = true;
		        			for(var j = 0; j<$scope.group.contractUser.length; j++){
		        				if($chosenList[i].userId === $scope.group.contractUser[j].userId ||
		        						$chosenList[i].userId === $scope.currentUser.userId ){
		        					flag = false;
		        					break;
		        				}
		        			}
		        			if(flag){
		        				addUserIds.push($chosenList[i].userId);
		        			}
		        		}
		        		ContactsResource.addGroupUser($scope.group.groupId, addUserIds).success(function(){
    						TipsService.show("<span class='glyphicon glyphicon-ok'></span>&nbsp;添加成功");
    						queryData();
    					});
	        		}
	        	};
				
		        /**
		         * 点击其他区域关闭弹出框
		         */
		        $scope.closePopup = function(event){
		        	$(".div-card-info").css("display","none"); 
		        };
		        
//		        /**
//		         * 点击其他区域关闭弹出框
//		         */
//				$document.on('click', hide);
//				$scope.$on('$destory', function() {
//                    $document.off('click', hide);
//                });
//				function hide() {
//                    $(".div-card-info").css("display","none");
//                }
				
				/**
		         * 计算高度
		         */
		        function initHeight() {
//		        	var target = $(".groupHeight"),
//                    offset = target.offset();
//		        	target.css("height", $(window).height()- offset.top);
//		        	target.css("min-height", $(window).height()- offset.top);
//		        	target.css("width", $(window).width()- offset.left + 10);
		        	
		        	var target2 = $(".groupListHeight1"),
                    offset2 = target2.offset();
//		        	target2.css("min-height", $(window).height()- offset2.top);
		        	target2.css("max-height", $(window).height()- offset2.top + 48);
		        	
		        	var target4 = $(".groupList"),
                    offset4 = target4.offset();
		        	target4.css("min-height", $(window).height()- offset4.top);
		        }
		        
		        /**
		         * 事件广播，接收被点击的userId
		         */
		        $scope.$on("getUserId", function(event, userId){
		        	$scope.getUserByUserId(userId);
		        });
		        
		        /**
		         * 事件广播，刷新列表
		         */
		        $scope.$on("refreshList", function(event){
		        	queryData()
		        });
		        
		        /**
				 * 获取用户详情
				 */
				$scope.getUserByUserId = function(userId) {
					$scope.user = null;
		        	//通过id获取信息
		        	ContactsResource.getUserByUserId(userId).success(function(user){
		        		$scope.user = user;
		        		if($scope.currentUser.userId === userId){
			        		$scope.user.chat = true;
			        	}
		        		var userOrgList = user.userOrg;
		        		if(userOrgList && userOrgList.length > 0){
		        			var allPostName = userOrgList[0].postName;
		        			for (var i = 1; i < userOrgList.length; i++) {
		        				allPostName += "、" + userOrgList[i].postName;
			        		}
		        			if(allPostName.length > 12){
		        				$scope.user.allPostName = allPostName.substring(0, 12) + "...";
		        			} else {
		        				$scope.user.allPostName = allPostName;
		        			}
		        		}
		        		
					});
		        };
		        
		        /**
		         * 显示/隐藏用户全组织
		         */
		        $scope.changeUserOrg = function(flag) {
		        	$timeout(function () {
		        		if (flag) { //显示
		        			var objDiv = $("#mydiv1"), position = objDiv.position(), len = 0;
							var top = objDiv.offset().top - objDiv.scrollParent().scrollTop();
							
							var leng = 0;
							var userOrgList = $scope.user.userOrg;
							if(userOrgList && userOrgList.length < 4){
								leng = 40 * userOrgList.length;
							} else {
								leng = 170;
							}
							//判断超出
							if (top + objDiv.outerHeight() + leng > $(window).height()) {
								objDiv.css("top", position.top - leng + "px");
								$("#post").fadeOut(function(){
									$("#org").slideDown("slow");
								});
							}else{
								$("#post").fadeOut(function(){
									$("#org").slideDown("slow");
								});
							}
		        		}else{
		        			$("#org").slideUp(function(){
		        				$("#post").fadeIn("slow");
		        			});
		        		}
		        	}, 300);
		        };
		        
		        /**
		         * 发起会话
		         */
                if (!attrs.toChat) {
                    $scope.selectSearch = function selectSearch(item) {
                        var id = {};
                        if (item.userId) {
                            id.userId = item.userId;
                        } else if (item.groupId) {
                            id.groupId = item.groupId;
                        }
                        // 会话页
                        ChatResource.query(id, null, 1).success(function (topic) {
                            $state.go('home.chat.msg', {
                                id: topic.topicId
                            });
                        });
                    };
                }
			}
		};
	}

	directive.$inject = deps;
	return app.lazy.directive('fcGroupItem', directive);
});